﻿#include "InputStream.h"
#include "lang/Exception.h"
#include "lang/Math.h"
using namespace yzrilyzr_array;
using namespace yzrilyzr_lang;
namespace yzrilyzr_io{
	InputStream::InputStream()=default;
	InputStream::~InputStream()=default;
	u_index InputStream::read(ByteArray & b){
		return read(b, 0, b.length);
	}
	u_index InputStream::read(ByteArray & b, u_index off, u_index len){
		if(len == 0){
			return 0;
		}
		int32_t c=read();
		if(c == -1){
			return -1;
		}
		b[off]=(int8_t)c;
		u_index i=1;
		try{
			for(;i < len;i++){
				c=read();
				if(c == -1){
					break;
				}
				b[off + i]=(int8_t)c;
			}
		} catch(Exception ee){
		}
		readCounter+=i;
		return i;
	}
	void InputStream::reset(){
		throw Exception("mark/reset not supported");
	}
	bool InputStream::markSupported(){
		return false;
	}
	void InputStream::mark(u_index readlimit){}
	void InputStream::close(){}
	u_index InputStream::available(){
		return 0;
	}
	u_index InputStream::skip(u_index n){
		u_index remaining=n;
		u_index nr;
		if(n <= 0){
			return 0;
		}
		u_index size=Math::min(MAX_SKIP_BUFFER_SIZE, remaining);
		ByteArray skipBuffer(size);
		while(remaining > 0){
			nr=read(skipBuffer, 0, (u_index)Math::min(size, remaining));
			if(nr < 0){
				break;
			}
			remaining-=nr;
		}
		return n - remaining;
	}
}